package com.witmore.ftp.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.witmore.ftp.db.entity.FtpUserDO;
import com.witmore.ftp.db.mapper.FtpUserMapper;
import com.witmore.ftp.web.vo.UserQueryVO;
import com.jk.common.response.ResponseResult;
import com.jk.common.response.ResponsePageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * FTP用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ftp/users")
@RequiredArgsConstructor
public class FtpUserController {

    private final FtpUserMapper ftpUserMapper;

    /**
     * 获取用户列表（分页）
     */
    @GetMapping
    public ResponsePageResult<FtpUserDO> getUsers(UserQueryVO queryVO) {

        // 设置默认分页参数
        if (queryVO.getPage() == null || queryVO.getPage() <= 0) {
            queryVO.setPage(1);
        }
        if (queryVO.getSize() == null || queryVO.getSize() <= 0) {
            queryVO.setSize(10);
        }

        Page<FtpUserDO> pageObj = new Page<>(queryVO.getPage(), queryVO.getSize());
        LambdaQueryWrapper<FtpUserDO> queryWrapper = new LambdaQueryWrapper<FtpUserDO>()
                .like(queryVO.getUsername() != null && !queryVO.getUsername().trim().isEmpty(), 
                      FtpUserDO::getUsername, queryVO.getUsername() != null ? queryVO.getUsername().trim() : null)
                .eq(queryVO.getEnabled() != null, FtpUserDO::getEnabled, queryVO.getEnabled())
                .like(queryVO.getHomeDirectory() != null && !queryVO.getHomeDirectory().trim().isEmpty(), 
                      FtpUserDO::getHomeDirectory, queryVO.getHomeDirectory() != null ? queryVO.getHomeDirectory().trim() : null)
                .eq(queryVO.getMaxConnections() != null, FtpUserDO::getMaxConnections, queryVO.getMaxConnections())
                .eq(queryVO.getWritePermission() != null, FtpUserDO::getWritePermission, queryVO.getWritePermission())
                .ge(queryVO.getStartTime() != null && !queryVO.getStartTime().trim().isEmpty(), 
                    FtpUserDO::getCreateTime, queryVO.getStartTime() != null ? queryVO.getStartTime().trim() : null)
                .le(queryVO.getEndTime() != null && !queryVO.getEndTime().trim().isEmpty(), 
                    FtpUserDO::getCreateTime, queryVO.getEndTime() != null ? queryVO.getEndTime().trim() : null)
                .eq(FtpUserDO::getIsDeleted, 0);

        // 处理排序
        if (queryVO.getSortField() != null && !queryVO.getSortField().isEmpty()) {
            if ("DESC".equalsIgnoreCase(queryVO.getSortOrder())) {
                queryWrapper.orderByDesc(getUserFieldFunction(queryVO.getSortField()));
            } else {
                queryWrapper.orderByAsc(getUserFieldFunction(queryVO.getSortField()));
            }
        } else {
            queryWrapper.orderByDesc(FtpUserDO::getCreateTime);
        }

        Page<FtpUserDO> result = ftpUserMapper.selectPage(pageObj, queryWrapper);
        return ResponsePageResult.success(result);
    }

    /**
     * 获取所有启用的用户（不分页）
     */
    @GetMapping("/enabled")
    public ResponseResult<List<FtpUserDO>> getEnabledUsers() {
        LambdaQueryWrapper<FtpUserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FtpUserDO::getEnabled, true)
                   .eq(FtpUserDO::getIsDeleted, 0)
                   .orderByAsc(FtpUserDO::getUsername);

        List<FtpUserDO> users = ftpUserMapper.selectList(queryWrapper);
        return ResponseResult.success(users);
    }

    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{id}")
    public ResponseResult<FtpUserDO> getUserById(@PathVariable Integer id) {
        FtpUserDO user = ftpUserMapper.selectById(id);
        if (user == null || user.getIsDeleted() == 1) {
            return ResponseResult.fail(404, "用户不存在");
        }
        return ResponseResult.success(user);
    }

    /**
     * 创建新用户
     */
    @PostMapping
    public ResponseResult<FtpUserDO> createUser(@RequestBody FtpUserDO user) {
        try {
            // 检查用户名是否已存在
            LambdaQueryWrapper<FtpUserDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FtpUserDO::getUsername, user.getUsername())
                       .eq(FtpUserDO::getIsDeleted, 0);
            
            FtpUserDO existingUser = ftpUserMapper.selectOne(queryWrapper);
            if (existingUser != null) {
                return ResponseResult.fail(400, "用户名已存在");
            }

            // 设置默认值
            if (user.getEnabled() == null) {
                user.setEnabled(true);
            }
            if (user.getMaxConnections() == null) {
                user.setMaxConnections(5);
            }
            if (user.getMaxConnectionsPerIp() == null) {
                user.setMaxConnectionsPerIp(2);
            }
            if (user.getWritePermission() == null) {
                user.setWritePermission(true);
            }
            if (user.getHomeDirectory() == null || user.getHomeDirectory().isEmpty()) {
                user.setHomeDirectory("/users/" + user.getUsername());
            }

            // 设置创建信息
            user.setCreator(1); // TODO: 从当前登录用户获取
            user.setUpdator(1);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setIsDeleted(0);

            ftpUserMapper.insert(user);
            log.info("Created new FTP user: {}", user.getUsername());
            
            return ResponseResult.success(user);
        } catch (Exception e) {
            log.error("Failed to create user: {}", user.getUsername(), e);
            return ResponseResult.fail(500, "创建用户失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ResponseResult<FtpUserDO> updateUser(@PathVariable Integer id, @RequestBody FtpUserDO user) {
        try {
            FtpUserDO existingUser = ftpUserMapper.selectById(id);
            if (existingUser == null || existingUser.getIsDeleted() == 1) {
                return ResponseResult.fail(404, "用户不存在");
            }

            // 如果要修改用户名，检查新用户名是否已存在
            if (!existingUser.getUsername().equals(user.getUsername())) {
                LambdaQueryWrapper<FtpUserDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FtpUserDO::getUsername, user.getUsername())
                           .eq(FtpUserDO::getIsDeleted, 0)
                           .ne(FtpUserDO::getId, id);
                
                FtpUserDO duplicateUser = ftpUserMapper.selectOne(queryWrapper);
                if (duplicateUser != null) {
                    return ResponseResult.fail(400, "用户名已存在");
                }
            }

            // 更新字段
            user.setId(id);
            user.setUpdator(1); // TODO: 从当前登录用户获取
            user.setUpdateTime(LocalDateTime.now());

            ftpUserMapper.updateById(user);
            log.info("Updated FTP user: {}", user.getUsername());
            
            return ResponseResult.success(user);
        } catch (Exception e) {
            log.error("Failed to update user: {}", id, e);
            return ResponseResult.fail(500, "更新用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteUser(@PathVariable Integer id) {
        try {
            FtpUserDO existingUser = ftpUserMapper.selectById(id);
            if (existingUser == null || existingUser.getIsDeleted() == 1) {
                return ResponseResult.fail(404, "用户不存在");
            }

            // 逻辑删除
            FtpUserDO user = new FtpUserDO();
            user.setId(id);
            user.setIsDeleted(1);
            user.setUpdator(1); // TODO: 从当前登录用户获取
            user.setUpdateTime(LocalDateTime.now());

            ftpUserMapper.updateById(user);
            log.info("Deleted FTP user: {}", existingUser.getUsername());
            
            return ResponseResult.success(null);
        } catch (Exception e) {
            log.error("Failed to delete user: {}", id, e);
            return ResponseResult.fail(500, "删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/{id}/status")
    public ResponseResult<Void> toggleUserStatus(@PathVariable Integer id, @RequestParam Boolean enabled) {
        try {
            FtpUserDO existingUser = ftpUserMapper.selectById(id);
            if (existingUser == null || existingUser.getIsDeleted() == 1) {
                return ResponseResult.fail(404, "用户不存在");
            }

            FtpUserDO user = new FtpUserDO();
            user.setId(id);
            user.setEnabled(enabled);
            user.setUpdator(1); // TODO: 从当前登录用户获取
            user.setUpdateTime(LocalDateTime.now());

            ftpUserMapper.updateById(user);
            log.info("{} FTP user: {}", enabled ? "Enabled" : "Disabled", existingUser.getUsername());
            
            return ResponseResult.success(null);
        } catch (Exception e) {
            log.error("Failed to toggle user status: {}", id, e);
            return ResponseResult.fail(500, "修改用户状态失败: " + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/password")
    public ResponseResult<Void> resetPassword(@PathVariable Integer id, @RequestParam String newPassword) {
        try {
            FtpUserDO existingUser = ftpUserMapper.selectById(id);
            if (existingUser == null || existingUser.getIsDeleted() == 1) {
                return ResponseResult.fail(404, "用户不存在");
            }

            FtpUserDO user = new FtpUserDO();
            user.setId(id);
            user.setPassword(newPassword);
            user.setUpdator(1); // TODO: 从当前登录用户获取
            user.setUpdateTime(LocalDateTime.now());

            ftpUserMapper.updateById(user);
            log.info("Reset password for FTP user: {}", existingUser.getUsername());
            
            return ResponseResult.success(null);
        } catch (Exception e) {
            log.error("Failed to reset password for user: {}", id, e);
            return ResponseResult.fail(500, "重置密码失败: " + e.getMessage());
        }
    }

    /**
     * 根据字段名获取对应的字段函数
     */
    private com.baomidou.mybatisplus.core.toolkit.support.SFunction<FtpUserDO, ?> getUserFieldFunction(String fieldName) {
        switch (fieldName) {
            case "username":
                return FtpUserDO::getUsername;
            case "enabled":
                return FtpUserDO::getEnabled;
            case "homeDirectory":
                return FtpUserDO::getHomeDirectory;
            case "maxConnections":
                return FtpUserDO::getMaxConnections;
            case "writePermission":
                return FtpUserDO::getWritePermission;
            case "createTime":
                return FtpUserDO::getCreateTime;
            case "updateTime":
                return FtpUserDO::getUpdateTime;
            default:
                return FtpUserDO::getCreateTime;
        }
    }
}
